﻿#include <iostream>
#include <event2/event.h>
#include <string.h>
#include <event2/listener.h>

#include "util/common_util.h"
#include "thread/thread_pool.h"
#include "thread/thread.h"
#include "ftptask/task_base.h"
#include "ftptask/task_factory.h"


#define SPORT 21
#define BUFS 1024


/*
 * @ hsby 接待连接的回调函数
 */
void listen_cb(struct evconnlistener *ev, evutil_socket_t s, struct sockaddr *addr, int socklen, void *arg) {
	LOGDEBUG("main Thread At listen_cb");
	TaskBase *task = TaskFactorySgt.CreateTask();
	task->sock = s;
	ThreadPoolSgt.Dispatch(task);
}

int main() {

    /*
     * @ hsby 初始化线程池
     */
	ThreadPoolSgt.Init(10);

	event_base *base = event_base_new();
	if (!base)
        exit(-1);

    /*
     * @ hsby 创建libevent上下文
     */
	sockaddr_in sin;
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(SPORT);

    /*
     * @ hsby 创建监听事件
     */
	evconnlistener *ev = evconnlistener_new_bind(
		base,											// libevent的上下文
		listen_cb,										//接收到连接的回调函数
		base,											//回调函数获取的参数 arg
		LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE,	//地址重用，evconnlistener关闭同时关闭socket
		10,										//连接队列大小，对应listen函数
		(sockaddr*)&sin,								//绑定的地址和端口
		sizeof(sin));

	if (base) {
        LOGDEBUG("begin to listen...");
		event_base_dispatch(base);
	}
	if (ev)
		evconnlistener_free(ev);
	if (base)
		event_base_free(base);
	LOGDEBUG("server end");
	return 0;
}

